package com.jxwifi.cloud.quickclean.login;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.content.LocalBroadcastManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.idroid.utils.TextColorUtil;
import com.idroid.widget.LoadDialog;
import com.idroid.widget.Toaster;
import com.jxwifi.cloud.quickclean.MainActivity;
import com.jxwifi.cloud.quickclean.R;
import com.jxwifi.cloud.quickclean.app.AccountMgr;
import com.jxwifi.cloud.quickclean.app.ClientBasicActivity;
import com.jxwifi.cloud.quickclean.app.StateUtils;
import com.jxwifi.cloud.quickclean.bean.RespBaseBean;
import com.jxwifi.cloud.quickclean.utils.ToastUtils;
import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.tencent.tauth.IUiListener;
import com.tencent.tauth.Tencent;
import com.tencent.tauth.UiError;
import com.umeng.analytics.MobclickAgent;

import org.simple.eventbus.Subscriber;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.trinea.android.common.util.REPattern;

/**
 * Created by Administrator on 2019/6/3.
 */

public class LoginActivity extends ClientBasicActivity implements LoginView,IUiListener {

    @Bind(R.id.et_login_cleaning_phone)
    EditText mEtLoginCleaningPhone;
    @Bind(R.id.et_login_cleaning_verification)
    EditText mEtLoginCleaningVerification;
    @Bind(R.id.tv_login_obtain_verification)
    TextView mTvLoginObtainVerification;
    @Bind(R.id.tv_login_button)
    TextView mTvLoginButton;
    @Bind(R.id.img_weixin_images)
    ImageView mImgWeiXinImages;
    @Bind(R.id.img_selection_images)
    ImageView mImgSelectaionImages;
    @Bind(R.id.tv_login_explain)
    TextView mTvLoginExplain;
    @Bind(R.id.login_images)
    ImageView mlogin_images;

    private boolean mIsSelection = true;
    private LoginPresenter mPresenter;

    public LoadDialog mLoadDialog;
    private  Tencent mTencent;

    private long mClickFirstTime = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        ButterKnife.bind(this);
        openEventBus();
        mLoadDialog = new LoadDialog(mBaseContext);
        mPresenter = new LoginPresenter(mBaseContext, this,this);
        initView();
        //mPresenter.getVrifyImage();
    }

    public void initView() {
        mTvLoginButton.setClickable(false);
        if (!TextUtils.isEmpty(AccountMgr.getLastphone(mBaseContext))) {
            mEtLoginCleaningPhone.setText(AccountMgr.getLastphone(mBaseContext));
        }
        TextColorUtil.setTextColor(mBaseContext, mTvLoginExplain, "同意 《快洁帮用户协议》", " ", R.color.color_cleaning_text);
        mPresenter.ChangedPhone();
        mPresenter.ChangedVerification();
    }

    @OnClick({R.id.tv_login_obtain_verification, R.id.tv_login_button, R.id.img_qq_images, R.id.img_weixin_images
            , R.id.tv_login_explain, R.id.img_selection_images})
    void clickCK(View v) {
        switch (v.getId()) {
            //获取验证码
            case R.id.tv_login_obtain_verification:
                if (mEtLoginCleaningPhone.getText().toString().equals("")) {
                    Toaster.show(mBaseContext, "请输入手机号码");
                    return;
                }
                boolean isMobile = REPattern.isMobileNO(mEtLoginCleaningPhone.getText().toString());
                if (!isMobile) {
                    Toaster.show(mBaseContext, "请输入正确的手机号码");
                    return;
                }
                mLoadDialog.show();
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        mPresenter.validation();
                    }
                }, 1000);

                break;
            //登录
            case R.id.tv_login_button:

                if (mEtLoginCleaningPhone.getText().toString().equals("")) {
                    Toaster.show(mBaseContext, "请输入手机号码");
                    return;
                }
                boolean isMobile2 = REPattern.isMobileNO(mEtLoginCleaningPhone.getText().toString());
                if (!isMobile2) {
                    Toaster.show(mBaseContext, "请输入正确的手机号码");
                    return;
                }
                if (mEtLoginCleaningVerification.getText().toString().equals("")) {
                    Toaster.show(mBaseContext, "验证码不能为空");
                    return;
                }
                //作保存手机号码的操作
                if (!TextUtils.isEmpty(mEtLoginCleaningPhone.getText().toString())) {
                    AccountMgr.putLastPhone(mBaseContext, mEtLoginCleaningPhone.getText().toString());
                }

                mLoadDialog.show();
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        mPresenter.judge();
                        mLoadDialog.dismiss();
                    }
                }, 1000);
                MobclickAgent.onEvent(mBaseContext, "tv_login_button");
                break;
            //QQ登录 功能取消后期完善(现有的代码不删，以后有用)
            case R.id.img_qq_images:
               // mPresenter.qqLogin();
                mTencent = Tencent.createInstance(StateUtils.QQ_APPID, mBaseContext);
                mTencent.login(this, "all", this);
                break;
            //微信登录
            case R.id.img_weixin_images:
                mPresenter.wechat();
                MobclickAgent.onEvent(mBaseContext, "img_weixin_images");
                break;
            //协议
            case R.id.tv_login_explain:
                Intent intent = new Intent();
                intent.setClass(mBaseContext, UserloginActivity.class);
                startActivity(intent);
                break;
            //协议按钮
            case R.id.img_selection_images:
                if (mIsSelection) {
                    mIsSelection = false;
                    mImgSelectaionImages.setBackgroundResource(R.mipmap.icon_selectagreed_un);
                    //Glide.get(mBaseContext).clearMemory();
                    //LocalBroadcastManager.getInstance(getApplicationContext()).sendBroadcast(new Intent(EXITAPP));
                    //System.gc();
                } else {
                    mIsSelection = true;
                    mImgSelectaionImages.setBackgroundResource(R.mipmap.icon_selection);
                }
                mPresenter.TextNull();
                break;
        }
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
       // super.onActivityResult(requestCode, resultCode, data);
        //mTencent.onActivityResult(requestCode, resultCode, data);
        mTencent.onActivityResultData(requestCode, resultCode, data, this);
    }

    @Override
    public EditText getPhone() {
        return mEtLoginCleaningPhone;
    }

    @Override
    public EditText getVerification() {
        return mEtLoginCleaningVerification;
    }

    @Override
    public TextView getVer() {
        return mTvLoginObtainVerification;
    }

    @Override
    public ImageView getSlection() {
        return mImgSelectaionImages;
    }

    @Override
    public boolean getIsSelection() {
        return mIsSelection;
    }

    @Override
    public TextView getLoginButton() {
        return mTvLoginButton;
    }

    @Override
    public void onFailure(int errorCode, String msg) {
        Toast toast = Toast.makeText(mBaseContext, msg, Toast.LENGTH_SHORT);
        ToastUtils.showMyToast(toast, 3000);
        mTvLoginButton.setBackgroundResource(R.drawable.shap_bottom_buttom_selector);
        mTvLoginButton.setClickable(true);
    }

    @Override
    public void onSuccessIntent() {
        Intent intent = new Intent();
        intent.setClass(mBaseContext, MainActivity.class);
        startActivity(intent);
        finish();
    }

    @Override
    public void onSetTellIntent() {
        Intent intent = new Intent();
        intent.setClass(mBaseContext, BindPhoneActivity.class);
        startActivity(intent);
    }

    @Override
    public ImageView getLoginImages() {
        return mlogin_images;
    }

    @Override
    public void onComplete(Object o) {
        Log.w("oushuhua","onComplete "+o.toString());
        mPresenter.getQQLogin(o,mTencent);
    }

    @Override
    public void onCancel() {
        Toast toast = Toast.makeText(mBaseContext, "取消登录", Toast.LENGTH_SHORT);
        ToastUtils.showMyToast(toast, 3000);
        Log.w("oushuhua","onCancel ");
    }

    @Override
    public void onError(UiError uiError) {
        Toast toast = Toast.makeText(mBaseContext, "登录失败", Toast.LENGTH_SHORT);
        ToastUtils.showMyToast(toast, 3000);
        Log.w("oushuhua","onError ");
    }

    //微信登录回调
    @Subscriber(tag = "e-wx-success")
    private void getWXsuccess(RespBaseBean mBean) {
        if (mBean != null) {
            switch (mBean.getTyoe()) {
                case StateUtils.WE_CHAT_LOGIN:
                    String code = ((SendAuth.Resp) mBean.getBaseResp()).code;
                    mPresenter.requestLoginByWeChat(code);
                    break;
                case StateUtils.QQ_LOGIN:

                    break;
            }
        }
    }

    @Subscriber(tag = "e-wx-cancel")
    private void getWXcancel(RespBaseBean mBean) {
        if (mBean != null) {
            switch (mBean.getTyoe()) {
                case StateUtils.WE_CHAT_LOGIN:
                    Toast toast = Toast.makeText(mBaseContext, "取消登录", Toast.LENGTH_SHORT);
                    ToastUtils.showMyToast(toast, 3000);
                    break;
                case StateUtils.QQ_LOGIN:

                    break;
            }
        }
    }

    @Subscriber(tag = "e-wx-error")
    private void getWXerror(RespBaseBean mBean) {
        if (mBean != null) {
            switch (mBean.getTyoe()) {
                case StateUtils.WE_CHAT_LOGIN:
                    Toast toast = Toast.makeText(mBaseContext, "登录失败", Toast.LENGTH_SHORT);
                    ToastUtils.showMyToast(toast, 3000);
                    Log.w("oushuhua", "微信失败编码=" + mBean.getBaseResp().errCode + "失败原因==" + mBean.getBaseResp().errStr);
                    break;
                case StateUtils.QQ_LOGIN:

                    break;
            }
        }
    }

    @Override
    public void onBackPressed() {
        long secondTime = System.currentTimeMillis();
        if (secondTime - mClickFirstTime > 2000) {
            Toast.makeText(mBaseContext, "再按一次退出程序", Toast.LENGTH_SHORT).show();
            mClickFirstTime = secondTime;
            return;
        } else {
            Glide.get(mBaseContext).clearMemory();
            LocalBroadcastManager.getInstance(getApplicationContext()).sendBroadcast(new Intent(EXITAPP));
            System.gc();
        }
        super.onBackPressed();
    }
}
